package com.hkzhao.shixun.config;

import com.hkzhao.shixun.component.JwtAuthenticationTokenFilter;
import com.hkzhao.shixun.component.RestAuthenticationEntryPoint;
import com.hkzhao.shixun.component.RestfulAccessDenieddHandler;
import com.hkzhao.shixun.dto.CoreUserDetail;
import com.hkzhao.shixun.mbg.model.Coreuser;
import com.hkzhao.shixun.mbg.model.Userpermission;
import com.hkzhao.shixun.service.CoreUserSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.List;

/**
 * <h3>j2ee</h3>
 * <p>security配置类</p>
 *
 * @author : hkzhao
 * @date : 2020-06-05 12:44
 **/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private RestfulAccessDenieddHandler restfulAccessDenieddHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    private CoreUserSerivce coreUserSerivce;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and() //关闭session 因为使用 token 没必要
                .authorizeRequests()
                .antMatchers(HttpMethod.GET,       "/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/swagger-resources/**",
                        "/v2/api-docs/**")
                //允许对静态资源的五授权访问
                .permitAll()
                .antMatchers("/admin/login","/admin/register","/xwoUser/register","/xwoUser/login")
                .permitAll()
                .antMatchers(HttpMethod.OPTIONS)
                //跨域请求先进行一次options
                .permitAll()
                .anyRequest()
                .authenticated();
        //禁用缓存
        http.headers().cacheControl();
        //添加JWT filter
        http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权和未登录结果返回
        http.exceptionHandling()
                .accessDeniedHandler(restfulAccessDenieddHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Override
    @Bean
    public UserDetailsService userDetailsService(){
        return username->{
            Coreuser coreuser = coreUserSerivce.getCoreUserByusername(username);
            if(coreuser!=null) {
                List<Userpermission> permissionList = coreUserSerivce.getPermissionList(coreuser.getTokenid());
                String password  = coreUserSerivce.getPassword(username);
                return new CoreUserDetail(coreuser,permissionList,password);
            }throw new UsernameNotFoundException("用户名或者密码错误");
        };
    }
    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
        return new JwtAuthenticationTokenFilter();
    }
}